/**
 * Token管理工具类
 * 用于处理用户认证token的存储、获取和刷新
 */

interface TokenData {
  accessToken: string
  refreshToken: string
  expiresAt: number
}

class TokenManager {
  private readonly ACCESS_TOKEN_KEY = 'access_token'
  private readonly REFRESH_TOKEN_KEY = 'refresh_token'
  private readonly EXPIRES_AT_KEY = 'token_expires_at'

  /**
   * 设置访问令牌
   */
  setToken(token: string, expiresIn?: number): void {
    localStorage.setItem(this.ACCESS_TOKEN_KEY, token)
    
    if (expiresIn) {
      const expiresAt = Date.now() + expiresIn * 1000
      localStorage.setItem(this.EXPIRES_AT_KEY, expiresAt.toString())
    }
  }

  /**
   * 获取访问令牌
   */
  getToken(): string | null {
    return localStorage.getItem(this.ACCESS_TOKEN_KEY)
  }

  /**
   * 设置刷新令牌
   */
  setRefreshToken(refreshToken: string): void {
    localStorage.setItem(this.REFRESH_TOKEN_KEY, refreshToken)
  }

  /**
   * 获取刷新令牌
   */
  getRefreshToken(): string | null {
    return localStorage.getItem(this.REFRESH_TOKEN_KEY)
  }

  /**
   * 检查token是否过期
   */
  isTokenExpired(): boolean {
    const expiresAt = localStorage.getItem(this.EXPIRES_AT_KEY)
    if (!expiresAt) {
      return false // 如果没有过期时间，假设未过期
    }
    
    return Date.now() > parseInt(expiresAt)
  }

  /**
   * 获取有效的token（如果过期则尝试刷新）
   */
  async getValidToken(): Promise<string | null> {
    const token = this.getToken()
    
    if (!token) {
      return null
    }

    // 如果token未过期，直接返回
    if (!this.isTokenExpired()) {
      return token
    }

    // 尝试刷新token
    try {
      const newToken = await this.refreshToken()
      return newToken
    } catch (error) {
      console.error('Token refresh failed:', error)
      this.clearTokens()
      return null
    }
  }

  /**
   * 刷新token
   */
  private async refreshToken(): Promise<string> {
    const refreshToken = this.getRefreshToken()
    
    if (!refreshToken) {
      throw new Error('No refresh token available')
    }

    // 这里应该调用实际的刷新token API
    // 目前返回模拟的新token
    const newToken = 'refreshed-token-' + Date.now()
    const expiresIn = 3600 // 1小时
    
    this.setToken(newToken, expiresIn)
    
    return newToken
  }

  /**
   * 清除所有token
   */
  clearTokens(): void {
    localStorage.removeItem(this.ACCESS_TOKEN_KEY)
    localStorage.removeItem(this.REFRESH_TOKEN_KEY)
    localStorage.removeItem(this.EXPIRES_AT_KEY)
  }

  /**
   * 检查是否已登录
   */
  isLoggedIn(): boolean {
    const token = this.getToken()
    const refreshToken = this.getRefreshToken()
    
    return !!(token && refreshToken)
  }

  /**
   * 获取token数据
   */
  getTokenData(): TokenData | null {
    const accessToken = this.getToken()
    const refreshToken = this.getRefreshToken()
    const expiresAt = localStorage.getItem(this.EXPIRES_AT_KEY)

    if (!accessToken || !refreshToken) {
      return null
    }

    return {
      accessToken,
      refreshToken,
      expiresAt: expiresAt ? parseInt(expiresAt) : 0
    }
  }
}

// 导出单例实例
const tokenManager = new TokenManager()
export default tokenManager